package com.corpgovernment.travelstandard.controller;

import com.alibaba.fastjson.JSON;
import com.corpgovernment.api.organization.model.post.PostVo;
import com.corpgovernment.api.travelstandard.enums.CarSceneEnum;
import com.corpgovernment.api.travelstandard.enums.CarSwitchEnum;
import com.corpgovernment.api.travelstandard.enums.ControlTypeEnum;
import com.corpgovernment.api.travelstandard.enums.TravelStandardTypeEnum;
import com.corpgovernment.api.travelstandard.vo.MbTravelstandReasonCodeVo;
import com.corpgovernment.api.travelstandard.vo.RCListVo;
import com.corpgovernment.api.travelstandard.vo.TravelStandardPostVo;
import com.corpgovernment.api.travelstandard.vo.car.*;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.enums.ExceptionCodeEnum;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.service.IPostService;
import com.corpgovernment.travelstandard.entity.db.*;
import com.corpgovernment.travelstandard.impl.*;
import com.corpgovernment.travelstandard.utils.BeanConverUtil;
import com.corpgovernment.travelstandard.vo.CarManageResponseVo;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.DateUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("carTravelStandardManage")
public class CarTravelStandardManageController {

    private final static String CAR_TRAVEL_STANDARD_DEFAULT_NAME = "用车差旅标准";

    @Autowired
    private TravelStandardPostService standPostService;
    @Autowired
    private IPostService postService;
    @Autowired
    private MbTravelstandCarService mbTravelstandCarService;
    @Autowired
    private MbTravelstandReasonCodeService mbTravelstandReasonCodeService;
    @Autowired
    private MbTravelstandCarModelService mbTravelstandCarModelService;
    @Autowired
    private MbTravelstandCarDatetimeService mbTravelstandCarDatetimeService;
    @Autowired
    private MbTravelStandCarCityService mbTravelStandCarCityService;
    @Autowired
    private MbTravelStandCarAddressService mbTravelStandCarAddressService;
    @Autowired
    private MbTravelStandCarCrossCityService mbTravelStandCarCrossCityService;
    @Autowired
    private MbTravelStandCarTimesService mbTravelStandCarTimesService;

    /**
     * 新增
     *
     * @return
     */
    @RequestMapping("toAdd")
    public JSONResult toAdd(@RequestBody CarManageVo carManageVo) {
        String title = carManageVo.getTitle();
        if (StringUtils.isBlank(title)) {
            title = CAR_TRAVEL_STANDARD_DEFAULT_NAME;
        }
        String orgId = carManageVo.getOrgId();
        if (StringUtils.isBlank(orgId)) {
            throw new CorpBusinessException(ExceptionCodeEnum.Alert, "组织id不能为空");
        }
        MbTravelstandCarVo mbTravelstandCarVo = new MbTravelstandCarVo(
                null,
                orgId,
                title,
                CarSwitchEnum.ModelSwitch.N.getCode(),
                ControlTypeEnum.F.getCode(),
                CarSwitchEnum.PriceSwitch.N.getCode(),
                100,100,100,
                ControlTypeEnum.F.getCode(),
                "",
                "",
                CarSwitchEnum.DatetimeSwitch.N.getCode(),
                ControlTypeEnum.F.getCode(),
                CarSwitchEnum.CarCitySwitch.N.getCode(),
                ControlTypeEnum.F.getCode(),
                CarSwitchEnum.CarAddressSwitch.N.getCode(),
                ControlTypeEnum.F.getCode(),
                CarSwitchEnum.CarTimesSwitch.N.getCode(),
                ControlTypeEnum.F.getCode(),"E"
        );
        mbTravelstandCarVo.setProductSwitch("E");
        mbTravelstandCarService.insertTravelstandCar(mbTravelstandCarVo);
        //对应RC
        List<MbTravelstandReasonCodeVo> mbTravelstandReasonCodeVos = mbTravelstandReasonCodeService.list(new MbTravelstandReasonCodeVo() {{
            setTsId(mbTravelstandCarVo.getId());
        }});
        //获取相关车型信息
        List<MbTravelstandCarModelVo> mbTravelstandCarModelVos = mbTravelstandCarModelService.list(new MbTravelstandCarModelVo().setTsCarId(mbTravelstandCarVo.getId()));
        //获取用车管控时间
        List<MbTravelstandCarDatetime> mbTravelstandCarDatetimes = mbTravelstandCarDatetimeService.selectByTsid(mbTravelstandCarVo.getId().toString());
        //获取用车城市管控
        List<MbTravelStandCarCity> mbTravelStandCarCities = mbTravelStandCarCityService.selectByTsid(mbTravelstandCarVo.getId().toString(), TravelStandardTypeEnum.Car.getCode());
        //获取用车地点管控
        List<MbTravelStandCarAddress> mbTravelStandCarAddresses = mbTravelStandCarAddressService.selectByTsid(mbTravelstandCarVo.getId().toString());

        //获取用车城市配置[跨城]
        List<MbTravelStandCarCrossCity> mbTravelStandCarCrossCities = mbTravelStandCarCrossCityService.selectByTsid(mbTravelstandCarVo.getId().toString(), TravelStandardTypeEnum.Car.getCode());

        //获取用车次数配置
        MbTravelStandCarTimes mbTravelStandCarTimes = mbTravelStandCarTimesService.selectByTsid(mbTravelstandCarVo.getId());
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("carControl", BeanConverUtil.travelstandCarVoToCarManageVo(
                mbTravelstandCarVo, null,
                mbTravelstandReasonCodeVos,
                mbTravelstandCarModelVos,
                mbTravelstandCarDatetimes,
                mbTravelStandCarCities,
                mbTravelStandCarAddresses,
                mbTravelStandCarCrossCities,
                mbTravelStandCarTimes
        ));
        return JSONResult.success(returnMap);
    }


    @RequestMapping("save")
    public JSONResult addCarTravelStandard(@RequestBody CarManageVo carManageVo) {
        //CarManageVo tagerCarManageVo = JSON.parseObject(JSON.toJSONString(json),CarManageVo.class);
        mbTravelstandCarService.updateCarTravelStandardProperty(carManageVo);
        return JSONResult.ok();
    }


    @RequestMapping("delete")
    public JSONResult deleteCarTravelStandard(@RequestBody CarManageVo carManageVo) {
        String id = carManageVo.getId();
        if (StringUtils.isBlank(id)) {
            throw new CorpBusinessException(ExceptionCodeEnum.Alert, "id不能为空!");
        }
        mbTravelstandCarService.deleteTravelstandCar(Long.valueOf(id));
        return JSONResult.ok();
    }

    @RequestMapping("get")
    public JSONResult getCarTravelStandard(@RequestBody CarManageVo carManageVo) {
        String orgId = carManageVo.getOrgId();
        if (StringUtils.isBlank(orgId)) {
            throw new CorpBusinessException(ExceptionCodeEnum.Alert, "公司id不能为空");
        }
        //获取全部岗位
        List<PostVo> posts = postService.listPostByOrgId(orgId);
        //已选职位
        List<TravelStandardPostVo> travelStandardPostVos = standPostService.selectByTsTypeAndOrgId(TravelStandardTypeEnum.Car.getCode(), orgId);
        List<Long> jobScope = new ArrayList<>();
        for (TravelStandardPostVo travelStandardPostVo : travelStandardPostVos) {
            jobScope.add(travelStandardPostVo.getPostid());
        }
        //该组织下下所有用车差标
        List<CarManageVo> carManageVos = mbTravelstandCarService.listTravelstandCar(new MbTravelstandCarVo().setOrgId(orgId));
        //
        Map<String, List<CarManageVo>> sceneGroupMap = carManageVos.stream().filter(item -> StringUtils.isNotBlank(item.getSceneCode())).collect(Collectors.groupingBy(CarManageVo::getSceneCode));
        List<CarSceneVo> carSceneVos = new ArrayList<>();
        Arrays.stream(CarSceneEnum.values()).forEach(item -> {
            List<CarManageVo> carManageVoList = sceneGroupMap.get(item.getCode());
            List<String> jobIds = new ArrayList<>();
            if (!CollectionUtils.isEmpty(carManageVoList)) {
                jobIds = carManageVoList.stream().map(CarManageVo::getJobScopeId).collect(Collectors.toList());
            }
            carSceneVos.add(new CarSceneVo(item.getCode(), item.getName(), item.getDesc(), jobIds));
        });

        CarManageResponseVo responseVo = new CarManageResponseVo();
        responseVo.setCarControl(carManageVos);
        responseVo.setJobScopeSelectList(jobScope);
        responseVo.setJobScopeAllList(posts);
        responseVo.setCarSceneVos(carSceneVos);
        return JSONResult.success(responseVo);
    }

    @RequestMapping("updateRc")
    public JSONResult updateRCContext(@RequestBody RCListVo rcListVo) {
        rcListVo.setTsType(TravelStandardTypeEnum.Car.getCode());
        mbTravelstandReasonCodeService.updateTravelstandReasonCode(rcListVo);
        return JSONResult.ok();
    }

    @RequestMapping("updateStandardName")
    public JSONResult updateStandardNameByID(@RequestBody CarManageVo carManageVo) {
        String id = carManageVo.getId();
        if (StringUtils.isBlank(id)) {
            throw new CorpBusinessException(ExceptionCodeEnum.Alert, "id不能为空");
        }
        String title = carManageVo.getTitle();
        if (StringUtils.isBlank(title)) {
            throw new CorpBusinessException(ExceptionCodeEnum.Alert, "标题不能为空");
        }
        mbTravelstandCarService.updateStandardName(Long.valueOf(id), title);
        return JSONResult.ok();
    }

    @RequestMapping("getTravelStandardDetail")
    public JSONResult<CarManageSoaVo> getTravelStandardDetail(@RequestParam(value = "uid") String uid, @RequestParam(value = "orgId") String orgId) {
        return JSONResult.success(mbTravelstandCarService.getTravelStandardDetail(uid, orgId));
    }

    @RequestMapping("selectTravelstandCarByOrgIdAndPostId")
    public JSONResult selectTravelstandCarByOrgIdAndPostId(@RequestBody CarTravelstandDto request) {
        return JSONResult.success(mbTravelstandCarService.selectTravelstandCarByOrgIdAndPostId(request));
    }

    @RequestMapping("selectCarDatetimeByIds")
    public JSONResult selectCarDatetimeByIds(@RequestBody CarDatetimeDto requestVo) {
        List<MbTravelstandCarDatetime> mbTravelstandCarDatetimes = mbTravelstandCarDatetimeService.selectByTsids(requestVo.getTsIds());
        List<CarDatetimeVo> datetimeVos = new ArrayList<>();

        for (int i = 0; i <mbTravelstandCarDatetimes.size() ; i++) {
            MbTravelstandCarDatetime item = mbTravelstandCarDatetimes.get(i);
            CarDatetimeVo target = new CarDatetimeVo();
            target.setTsid(item.getTsid());
            target.setIsWork(item.getIsWork());
            target.setStartTime(item.getStartTime());
            target.setEndTime(item.getEndTime());
            target.setStatus(item.getStatus());
            target.setIsNextDay(item.getIsNextDay());
            TimesVo _times = new TimesVo();
            String[] startParts = item.getStartTime().split(":");
            String[] endParts = item.getEndTime().split(":");
            _times.setStartHour(startParts[0]);
            _times.setStartMin(startParts[1]);
            _times.setEndHour(String.valueOf(Integer.parseInt(endParts[0])+ 24* item.getIsNextDay()));
            _times.setEndMin(endParts[1]);
            target.set_times(_times);
            datetimeVos.add(target);
        }

        return JSONResult.success(datetimeVos);
    }

    @RequestMapping("getTravelStandardDetailByTsId")
    public JSONResult<CarManageSoaVo> getTravelStandardDetailByTsId(@RequestParam(value = "tsId") Long tsId) {
        return JSONResult.success(mbTravelstandCarService.getTravelStandardDetailNew(tsId));
    }

    @RequestMapping("getTravelStandardDetailByPostId")
    public JSONResult<CarManageSoaVo> getTravelStandardDetailByPostId(@RequestParam(value = "postId") Integer postId) {
        return JSONResult.success(mbTravelstandCarService.getTravelStandardDetailByPostId(postId));
    }

}
